#!python3
# -*- coding: utf-8 -*-
# works on windows XP, 7, 8, 8.1 and 10
import os
import sys
import time
import subprocess
import unittest
from HTMLTestRunner1 import HTMLTestRunner

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))  # not required after 'pip install uiautomation'
import uiautomation as auto

auto.uiautomation.DEBUG_EXIST_DISAPPEAR = True  # set it to False and try again, default is False
auto.uiautomation.DEBUG_SEARCH_TIME = True  # set it to False and try again, default is False
auto.uiautomation.TIME_OUT_SECOND = 7  # global time out
print('timeout: {}, old {} is not effective'.format(auto.uiautomation.TIME_OUT_SECOND, auto.TIME_OUT_SECOND))
auto.uiautomation.SetGlobalSearchTimeout(6)  # global time out
print('timeout: {}, old {} is not effective'.format(auto.uiautomation.TIME_OUT_SECOND, auto.TIME_OUT_SECOND))

class MyTestCase1(unittest.TestCase):
    def setUp(self):
        print("启动Case1")
    def test_case1(self):
        print("这是case1测试用例1")
        result = TestDisplayMark()
        self.assertTrue(result)
    def test_case2(self):
        print("这是case1测试用例2")
        # 断言
        self.assertEqual(1, 1, '不相等')
    def tearDown(self):
        print("结束Case1")

def TestDemo():
    # Desc is not a valid search property, but it can be used for debug printing
    utkWindow = auto.WindowControl(searchDepth=1, ClassName='MainWindow', Name='UTK')
    if not utkWindow.Exists(0, 0):
        subprocess.Popen('D:/github/build-utkwidget-Desktop_Qt_5_15_2_MinGW_64_bit-Debug/examples/Demo.exe')
    utkWindow.SetActive()
    titlebar = utkWindow.GroupControl(ClassName='UTitleBar')
    titlebar.GetChildren()[2].Click()
    menu = auto.WindowControl(ClassName='UMenu', Name='UTK')
    menu.MenuItemControl(Name='About').Click()
    dialog = utkWindow.WindowControl(ClassName='UAboutDialog')
    time.sleep(1)
    dialog.ButtonControl(ClassName='UStyleButton').Click()
    time.sleep(3)
    utkWindow.ListItemControl(Name='Label').Click()
    searchEdit = utkWindow.EditControl(ClassName='ULineEdit')
    searchEdit.GetValuePattern().SetValue('按钮')
    auto.Click(searchEdit.BoundingRectangle.left + 216, searchEdit.BoundingRectangle.top + 18)
    utkWindow.ListItemControl(Name='datetime').Click()
    slider = utkWindow.SliderControl(ClassName='USlider')
    slider.GetRangeValuePattern().SetValue(10)
    slider.GetRangeValuePattern().SetValue(30)
    slider.GetRangeValuePattern().SetValue(60)
    slider.GetRangeValuePattern().SetValue(100)
    time.sleep(3)
    # utkWindow.ListItemControl(AutomationId='Scientific').Click()
    # utkWindow.ButtonControl(AutomationId='clearButton').Click()
    # if 0:
    #     char2Button = {key: calcWindow.ButtonControl(AutomationId=char2Id[key], Desc='Button ' + key) for key in char2Id}
    # else:
    #     # Run faster because it only walk calc window once
    #     id2char = {v: k for k, v in char2Id.items()}
    #     char2Button = {}
    #     for c, d in auto.WalkControl(calcWindow):
    #         if c.AutomationId in id2char:
    #             char2Button[id2char[c.AutomationId]] = c
    # Calc(calcWindow, char2Button, '1234 * (4 + 5 + 6) - 78 / 90.8')
    # Calc(calcWindow, char2Button, '3*3+4*4')
    # Calc(calcWindow, char2Button, '2*3.14159*10')
    utkWindow.CaptureToImage('utk.png', 7, 0, -14, -7)  # on windows 10, 7 pixels of windows border are transparent
    utkWindow.Disappears(1)
    utkWindow.GetWindowPattern().Close()
    utkWindow.Exists(1)
def getImage(window, imgPath):
    timestrmap = time.strftime('%Y%m%d_%H.%M.%S')
    imgPath = os.path.join(imgPath, '%s.png' % str(timestrmap))
    window.CaptureToImage(imgPath, 7, 0, -14, -7)
    print('screenshot:', timestrmap, '.png')
def TestDisplayMark():
    # Desc is not a valid search property, but it can be used for debug printing
    displayMarkWindow = auto.WindowControl(searchDepth=1, ClassName='ScreenMeasureToolsNS::MainWindow', Name='DisplayMark')
    if not displayMarkWindow.Exists(0, 0):
        process = subprocess.Popen('C:/Program Files (x86)/Nova Star/Display Mark/Bin/DisplayMark.exe')
    displayMarkWindow.SetActive()
    displayMarkWindow.ButtonControl(ClassName='NStyleButton', Name='新建工程').Click()
    time.sleep(0.5)
    projectCreateDialog = displayMarkWindow.WindowControl(searchDepth=1, ClassName='ProjectCreateDialog')
    nameEdit = projectCreateDialog.EditControl(ClassName='NLineDialogEdit')
    nameEdit.GetValuePattern().SetValue('按钮')
    time.sleep(0.5)
    projectCreateDialog.ButtonControl(ClassName='NStyleButton', Name='确定').Click()
    time.sleep(0.5)
    topNavigationBar = displayMarkWindow.CustomControl(ClassName='TopNavigationBar')
    topNavigationBar.ButtonControl(ClassName='NStyleButton', Name='返回首页 ').Click()
    time.sleep(0.2)
    modelDialog = displayMarkWindow.WindowControl(ClassName='ModelDialogUI')
    modelDialog.ButtonControl(ClassName='PushButtonEx', Name='确定').Click()
    time.sleep(0.2)
    path = "./report/images"
    getImage(displayMarkWindow, path)
    projectCardView = displayMarkWindow.ListControl(ClassName='ProjectCardView')
    item = projectCardView.ListItemControl(Name='按钮')
    isok = item.Exists(0, 0)
    process.kill()
    return isok


if __name__ == '__main__':
    # 1.测试用例集合1
    suite1 = unittest.TestLoader().loadTestsFromTestCase(MyTestCase1)
    # 2.加载所有的被测试对象：将所有的测试用例集合，加在一起
    suite = unittest.TestSuite([suite1])

    report_path = "./report/reportDemo.html"
    f = open(report_path, 'wb')
    runner = HTMLTestRunner(stream=f,
                                title='自动化测试报告',
                                description='generated by HTMLTestRunner.',
                                verbosity=2,
                                tester='helei'
                            )
    runner.run(suite)
    f.close()


